package com.example.shixun1.adapter;

import android.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.shixun1.R;
import com.example.shixun1.model.Article;
import java.util.List;

public class ArticleAdapter extends RecyclerView.Adapter<ArticleAdapter.ViewHolder> {
    private final List<Article> articles;
    private final OnItemClickListener listener;
    private final OnItemDeleteListener deleteListener;

    public interface OnItemClickListener {
        void onItemClick(Article article);
    }

    public interface OnItemDeleteListener {
        void onItemDelete(Article article);
    }

    public ArticleAdapter(List<Article> articles, OnItemClickListener listener, OnItemDeleteListener deleteListener) {
        this.articles = articles;
        this.listener = listener;
        this.deleteListener = deleteListener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_article, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Article article = articles.get(position);
        holder.tvTitle.setText(article.getTitle());
        holder.tvContent.setText(article.getContent());

        holder.itemView.setOnClickListener(v -> listener.onItemClick(article));

        holder.btnDelete.setOnClickListener(v -> {
            new AlertDialog.Builder(v.getContext())
                    .setTitle("删除文章")
                    .setMessage("确定要删除这篇文章吗？")
                    .setPositiveButton("确定", (dialog, which) -> {
                        deleteListener.onItemDelete(article);
                        articles.remove(position);
                        notifyItemRemoved(position);
                    })
                    .setNegativeButton("取消", null)
                    .show();
        });
    }

    @Override
    public int getItemCount() {
        return articles.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView tvTitle;
        TextView tvContent;
        ImageView btnDelete;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            tvTitle = itemView.findViewById(R.id.tv_article_title);
            tvContent = itemView.findViewById(R.id.tv_article_content);
            btnDelete = itemView.findViewById(R.id.btn_delete);
        }
    }
}